<?php

/**
 * Class Module_Task_Case
 *
 */
class Module_Task_Case
{
    //效验案件数据，组装数据添加
    public static function saveCaseHandler($data)
    {
        if (empty($data['case']) || empty($data['assets'])) {
            return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
        }
        $ssid = empty($data['ssid']) ? str_replace('.', '', uniqid('', true)) : $data['ssid'] ;
        $case = $data['case'];
        $assets = $data['assets'];
        $log = "ssid: ". $ssid;
        $log .= empty($case['detailId']) ? " pushCase " : "importCase ";
        try {
            $history = Module_Mediate_Case::getInstance()->getOne(['id'],["assetsId = {$assets['id']}","contractNo = '{$case['contractNo']}'","sysStatus = 1"]);
            //查看是否已经入库
            if (!empty($history)) {
                if(!empty($case['detailId'])){
                    Module_Mediate_ImportRecordDetail::getInstance()->updateSubmitStatus($case['detailId'],4,'案件已经存在');
                }
                Func_Log::write('saveCase', $log. 'case already exists', 'res= ' . json_encode($case));
                return ['code' => 4002, 'message' => '案件已经存在', 'data' => []];
            }
            $unique = [];
            //处理公债人
            $litigant = [];
            if(!empty($case['debtor'])){
                foreach ($case['debtor'] as $debtor){
                    $debtorTelephone = is_array($debtor['telephone']) ? $debtor['telephone'] : explode(',',$debtor['telephone']);
                    foreach ($debtorTelephone as $telephone){
                        $temp = $debtor['cardId'].$telephone;
                        if(!in_array($temp,$unique)){
                            $litigant[] = [
                                'litigantName' => $debtor['litigantName'],
                                'cardId' => $debtor['cardId'],
                                'telephone' =>$telephone,
                                'type' =>2,
                            ];
                        }
                    }
                }
            }
            //处理当事人
            $litigantTelephone = is_array($case['telephone']) ? $case['telephone']: explode(',',$case['telephone']);
            foreach ($litigantTelephone as $telephone){
                $temp = $case['cardId'].$telephone;
                if(!in_array($temp,$unique)){
                    $litigant[] = [
                        'litigantName' => $case['litigantName'],
                        'cardId' => $case['cardId'],
                        'telephone' =>$telephone,
                        'type' =>1,
                    ];
                }
            }
            //如果上传了调解员，自动分配
            $mediator = [];
            $remarks = '';
            if(!empty($case['mediatorName'])){
                $mediator = Module_User_Administrator::getInstance()->getOne(['id','name','mediationOrganId'],["name='{$case['mediatorName']}'"],true);
                if(empty($mediator)){
                    $mediator['name'] = $case['mediatorName'];
                    $remarks =  $case['mediatorName'].' 未匹配到系统调解员';
                }
            }
            $debtTargetDate =  empty($case['debtTargetDate']) || strtotime($case['debtTargetDate']) < 10000 ? date("Y-m-d") : $case['debtTargetDate'];
            $save_case = [
                'caseStatus' => 'case_audit',
                'MediateResult' => 'no_results',
                'assetsName' => $assets['name'],
                'assetsId' => $assets['id'],
                'mediationOrganId' => empty($mediator['mediationOrganId']) ? (empty($case['mediationOrganId']) ? 1 : $case['mediationOrganId']) : $mediator['mediationOrganId'] ,
                'mediatorId' => empty($mediator['id']) ? 0 : $mediator['id'],
                'mediatorName' => empty($mediator['name']) ? '' : $mediator['name'],
                'allocateTime' => empty($mediator['id']) ? 0 : time(),
                'caseSource' => empty($case['caseSource']) ? 1 : $case['caseSource'],
                'litigantName' =>implode(',',array_unique(array_column($litigant, 'litigantName'))),
                'cardId' => $case['cardId'],
                'assetType' => empty($case['assetType']) ? 1 : $case['assetType'],
                'disputeType' => empty($case['disputeType']) ? 1 : $case['disputeType'],
                'caseType' => empty($case['caseType']) ? 1 : $case['caseType'],
                'batchName' => empty($case['batchName']) ? '' : $case['batchName'],
                'batshId' => $case['batshId'],
                'contractNo' => empty($case['contractNo']) ? '' : $case['contractNo'],
                'debtAmount' => empty($case['debtAmount']) ? 0 : $case['debtAmount'],
                'debtInte' => empty($case['debtInte']) ? 0 : $case['debtInte'],
                'debtTotal' => empty($case['debtTotal']) ? 0 : $case['debtTotal'],
                'claimAmount' => empty($case['claimAmount']) ? 0 : $case['claimAmount'],
                'combinRate' => empty($case['combinRate']) ? 0 : $case['combinRate'],
                'putoutDate' => empty($case['putoutDate']) ? 0 : strtotime($case['putoutDate']),
                'overdueMonth' => Lib_Function::getInstance()->getM($case['overdueDate'],$debtTargetDate),
                'loanAmount' => empty($case['loanAmount']) ? 0 : $case['loanAmount'],
                'loanPlatform' => empty($case['loanPlatform']) ? '' : $case['loanPlatform'],
                'loanTerm' => empty($case['loanTerm']) ? 0 : $case['loanTerm'],
                'debtTargetDate' => empty($case['debtTargetDate']) ? 0 : strtotime($case['debtTargetDate']),
                'overdueDate' => empty($case['overdueDate']) ? 0 : strtotime($case['overdueDate']),
                'entrustExpireTime' => empty($case['entrustExpireTime']) ? 0 : strtotime($case['entrustExpireTime']),
                'importRecordId' => empty($case['importRecordId']) ? 0 : $case['importRecordId'],
                'caseLabel' => empty($case['caseLabel']) ? 0 : $case['caseLabel'],
                'mediationNum' => empty($case['mediationNum']) ? '' : $case['mediationNum'],
                'addTime' => time(),
                'updateTime' => time(),
                'remarks' => $remarks,
            ];

            $attach = $case['attachInfo'];
            $case_operation_log_arr =
                [
                    'status' =>'case_save',
                    'operationUid' => empty($data['operationUid']) ? 0 : $data['operationUid'],
                    'operationName' =>  empty($data['operationName']) ? "接口推送" : $data['operationName'],
                    'operationContent' =>'案件入库',
                    'remark' =>$case['caseSource']==1 ? "案件上传" : '接口推送',
                    'createTime' =>time(),
                ];
            $res = Module_Mediate_Case::getInstance()->insert($save_case,$litigant,$case_operation_log_arr,$attach);
            if(!$res){
                Func_Log::write('saveCase', $log . 'case save error', 'res= ' . json_encode($case));
                return ['code' => 400, 'message' => '案件入库失败', 'data' => []];
            }
            Module_Mediate_ImportRecordDetail::getInstance()->updateSubmitStatus($case['detailId'],3,'导入成功');
            Func_Log::write('saveCase', $log . 'case save success', 'res= ' . json_encode($case));
            return ['code' => 200, 'message' => '案件入库成功', 'data' => []];
        }catch (Error $err) {//捕获异常
            Func_Log::write('saveCase', $log . 'case save server error :'.$err, 'res= ' . json_encode($case));
            return ['code' => 501, 'message' => '案件入库失败', 'data' => []];
        }catch (Exception $e) {//捕获异常
            Func_Log::write('saveCase', $log . 'case save server error :'.$e, 'res= ' . json_encode($case));
            return ['code' => 501, 'message' => '案件入库失败', 'data' => []];
        }
    }
    //批量修改案件到期时间
    public static function updateEntrustTimeHandler($data){
        try {
            //接口推送
            if(!empty($data['dataType']) && $data['dataType'] == 'api') {
                if (empty($data['data']) || empty($data['client'])) {
                    return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
                }

                $ssid = empty($data['ssid']) ? str_replace('.', '', uniqid('', true)) : $data['ssid'];
                if (empty($data['data']['entrustExpireTime']) || (empty($data['data']['contractNo']) && empty($data['data']['batshId']))) {
                    Func_Log::write('updateEntrustTime', "ssid: " . $ssid . ' case save server error :', 'res= ' . json_encode($data));
                    return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
                }
                $assets = $data['assets'];
                if ($data['data']['contractNo']) {
                    $case = Module_Mediate_Case::getInstance()->getOne(['id'], ["assetsId = {$assets['id']}", "contractNo = '{$data['data']['contractNo']}'"]);
                    if(empty($case)){
                        Func_Log::write('updateEntrustTime', "ssid: " . $ssid . ' case save server error :', 'res= ' . json_encode($data));
                        return ['code' => 4000, 'message' => 'case is empty', 'data' => []];
                    }
                    $res = Module_Mediate_Case::getInstance()->updateStatusAddLogById(
                        [
                            'entrustExpireTime'=>strtotime($data['data']['entrustExpireTime']),
                            'updateTime'=>time(),
                            'id'=>$case['id'],
                        ],
                        [
                            'caseId' => $case['id'],
                            'status' => 'update_expire_time',
                            'operationUid' => 0,
                            'operationName' => '接口推送',
                            'operationContent' => '更新委案到期时间',
                            'remark' => '从' . date("Y-m-d H:i:s", $case['entrustExpireTime']) . '更新为' . $data['data']['entrustExpireTime'],
                            'createTime' => time(),
                        ]);
                    if(!$res){
                        Func_Log::write('updateEntrustTime', "ssid: " . $ssid . ' save error :', 'res= ' . json_encode($data));
                        return ['code' => 4000, 'message' => 'case is empty', 'data' => []];
                    }
                    Func_Log::write('updateEntrustTime', "ssid: " . $ssid . ' save success :', 'res= ' . json_encode($data));
                    return ['code' => 200, 'message' => 'case is empty', 'data' => []];
                }elseif ($data['data']['batshId']){
                    $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['id','entrustExpireTime'], ['where'=>["assetsId = {$assets['id']}", "batshId = '{$data['data']['batshId']}'"]]);
                    foreach ($cases as $case){
                        Module_Mediate_Case::getInstance()->updateStatusAddLogById(
                            [
                                'entrustExpireTime'=>strtotime($data['data']['entrustExpireTime']),
                                'id'=>$case['id'],
                            ],
                            [
                                'caseId' => $case['id'],
                                'status' => 'update_expire_time',
                                'operationUid' => 0,
                                'operationName' => '接口推送',
                                'operationContent' => '更新委案到期时间',
                                'remark' => '从' . date("Y-m-d H:i:s", $case['entrustExpireTime']) . '更新为' . $data['data']['entrustExpireTime'],
                                'createTime' => time(),
                            ]
                        );
                    }
                    Func_Log::write('updateEntrustTime', "ssid: " . $ssid . ' save success :', 'res= ' . json_encode($data));
                    return ['code' => 200, 'message' => 'case is empty', 'data' => []];
                }

            }else{//系统操作

            }
        }catch (Error $err) {//捕获异常
            Func_Log::write('updateEntrustTime', "ssid: ". $ssid . ' case save server error :'.$err, 'res= ' . json_encode($case));
            return ['code' => 501, 'message' => '案件入库失败', 'data' => []];
        }catch (Exception $e) {//捕获异常
            Func_Log::write('updateEntrustTime', "ssid: ". $ssid . ' case save server error :'.$e, 'res= ' . json_encode($case));
            return ['code' => 501, 'message' => '案件入库失败', 'data' => []];
        }

    }
    //根据caseId修改
    private static function updateEntrustTimeByCaseId($data){
        $res = Module_Mediate_Case::getInstance()->singleUpdate(['mediate_expire_time' => $data['mediate_expire_time'], 'id' => $case['id']]);
        if ($res) {
            Module_Mediate_CaseOperationLog::getInstance()->insert([
                'case_id' => $case['id'],
                'status' => 'update_expire_time',
                'operation_uid' => $data['operation_name'],
                'operation_name' => $data['operation_name'],
                'remark' => '从' . date("Y-m-d H:i:s", $case['mediate_expire_time']) . '更新为' . date("Y-m-d H:i:s", $data['mediate_expire_time']),
                'create_ts' => time(),
            ]);
            Func_Log::write('updateExpireTime', $case['id'] . 'update update_expire_time success', '从' . '从' . date("Y-m-d H:i:s", $case['mediate_expire_time']) . '更新为' . date("Y-m-d H:i:s", $data['mediate_expire_time']));
        }
        return $res;

    }
    //案件上传详情添加
    public static function addCaseUploadDetailHandler($data){

        if (!$data) {
            return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
        }
        $task_id = $data['task_id'];
        unset($data['task_id']);
        try {
            $recordDetailRes = Module_Mediate_ImportRecordDetail::getInstance()->singleInsert($data);
            if(!$recordDetailRes){
                Func_Log::write("addCaseUploadDetai", "task_id:: ".$task_id.' record_detail_insert_fail', json_encode($data));
            }
            return ['code' => 200, 'message' => 'success', 'data' => []];
        } catch (Exception $exception) {
            Func_Log::write("addCaseUploadDetai", "task_id:: ".$task_id.' record_detail_insert_error', json_encode($data).',error:'.$exception->getMessage());
            return ['code' => 500, 'message' => $exception, 'data' => []];
        }


    }
    //案件上传详情添加
    public static function addPublicCaseHandler($data){

        if (!$data) {
            return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
        }
        $task_id = $data['task_id'];
        unset($data['task_id']);
        try {
            $recordDetailRes = Module_Mediate_PublicCase::getInstance()->singleInsert($data);
            if(!$recordDetailRes){
                Func_Log::write("addCaseUploadDetai", "task_id:: ".$task_id.' record_detail_insert_fail', json_encode($data));
            }
            return ['code' => 200, 'message' => 'success', 'data' => []];
        } catch (Exception $exception) {
            Func_Log::write("addCaseUploadDetai", "task_id:: ".$task_id.' record_detail_insert_error', json_encode($data).',error:'.$exception->getMessage());
            return ['code' => 500, 'message' => $exception, 'data' => []];
        }


    }
    //添加操作日志
    public static function addOperateLogHandler($data){
        if (empty($data) || empty($data['caseId']) || empty($data['status']) || empty($data['operationUid'])  || empty($data['operationName']) ) {
            Func_Log::write("addOperateLog", ' param error', json_encode($data));
            return ['code' => 4000, 'message' => '缺少参数', 'data' => []];
        }
        try {
            $res = Module_Mediate_CaseOperationLog::getInstance()->singleInsert([
                'caseId' => $data['caseId'],
                'status' => $data['status'],
                'operationUid' => $data['operationUid'],
                'operationName' => $data['operationName'],
                'operationContent' => empty($data['operationContent']) ? '' :$data['operationContent'],
                'remark' =>  empty($data['remark']) ? '' :$data['remark'],
                'createTime' =>  empty($data['createTime']) ? time() :$data['createTime'],
            ]);
            if(!$res){
                Func_Log::write("addOperateLog", 'add error', json_encode($data));
            }
            return ['code' => 200, 'message' => 'success', 'data' => []];
        } catch (Exception $exception) {
            Func_Log::write("addOperateLog", 'add fatal error', json_encode($data).',error:'.$exception->getMessage());
            return ['code' => 500, 'message' => $exception, 'data' => []];
        }


    }
    //推送案件结果
    public static function caseauditHandler($data){
        if (empty($data['operationUid']) || empty($data['operationName']) || empty($data['caseId']) || empty($data['auditStatus'])) {
            Func_Log::write('caseaudit', 'param error',json_encode($data));
            return ['code' => 4000, 'message' => 'param error', 'data' => []];
        }

        $case = Module_Mediate_Case::getInstance()->getItemById($data['caseId']);
        if(empty($case)) {
            Func_Log::write('caseaudit', 'case empty','case id'.$data['caseId']);
            return ['code' => 4001, 'message' => 'case empty', 'data' => []];
        }
        if($data['auditStatus'] == 'pass'){
            $save_data = [
                'id'=>$case['id'],
                'caseStatus' => 'case_allocate',
                'updateTime' => time()
            ];
        }else{
            $save_data = [
                'id'=>$case['id'],
                'sysStatus' => 3,
                 'updateTime' => time()

            ];
        }
        $res = Module_Mediate_Case::getInstance()->updateStatusAddLogById(
            $save_data,
            [
                'caseId' => $case['id'],
                'status' => 'case_audit',
                'operationUid' => $data['operationUid'],
                'operationName' => $data['operationName'],
                'operationContent' =>"案件审核",
                'remark' => $data['auditStatus'] == 'pass' ? "案件审核通过" : "案件审核驳回",
                'createTime' => time(),
            ]
        );
        if($res){
            Func_Log::write('caseaudit', $data['auditStatus'] . ' scuess audit','case id'.$data['caseId']);
            return ['code' => 200, 'message' => 'success', 'data' => []];
        }
        Func_Log::write('caseaudit', $data['auditStatus'] . ' error audit','case id'.$data['caseId']);
        return true;

    }
}
